package com.cxs.musicplaywidget.service;

import com.cxs.musicplaywidget.MainAbility;
import com.cxs.musicplaywidget.ServiceAbility;
import com.cxs.musicplaywidget.commonevent.EventManager;
import com.cxs.musicplaywidget.data.MDevice;
import com.cxs.musicplaywidget.data.EventParam;
import com.cxs.musicplaywidget.service.idl.MyAgentProxy;
import com.cxs.musicplaywidget.util.LogUtils;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.app.Context;
import ohos.bundle.ElementName;
import ohos.rpc.IRemoteObject;

import java.util.*;

import static com.cxs.musicplaywidget.data.EventParam.EventAction.*;

public class ServiceManager {
    private static final String tag = ServiceManager.class.getSimpleName();
    private volatile static ServiceManager instance = null;
    private Context context;
    private static DeviceManager deviceManager;

    private ServiceManager(Context context) {
        this.context = context;
        init();
    }

    public static ServiceManager getInstance(Context context) {
        if (instance == null) {
            synchronized (ServiceManager.class) {
                if (instance == null) {
                    instance = new ServiceManager(context);
                }
            }
        }
        return instance;
    }

    public void init() {
        deviceManager = DeviceManager.getInstance(context);
        List<MDevice> deviceList = deviceManager.getDeviceList();
        if (deviceList.isEmpty()) {
            return;
        }
        connectService((byte)0);
    }

    public boolean isConnected(byte deviceIndex) {
        deviceManager = DeviceManager.getInstance(context);
        return deviceManager.isConnected(deviceIndex);
    }


    public synchronized boolean connectService(byte deviceIndex) {
        deviceManager = DeviceManager.getInstance(context);
        MDevice device = deviceManager.getDevice(deviceIndex);
        if (device == null) {
            return false;
        }
        EventManager.publishEvent(new EventParam(CONNECTING, deviceIndex));
        if (isConnected(deviceIndex)) {
            deviceManager.setCurrentIndex(deviceIndex);
                MyAgentProxy proxy = device.proxy();
                if (proxy != null) {
                    proxy.addEvent(new EventParam(CONNECTED, deviceIndex));
                    proxy.addEvent(new EventParam(GET_PLAY_LIST, proxy.getPlayList()));
                    proxy.addEvent(new EventParam(GET_PLAYER_STATE, deviceIndex));
                    proxy.addEvent(new EventParam(GET_VOLUME));
                    proxy.start();
                    return true;
                }
        }
        AbilityConnection abilityConnection = new AbilityConnection(deviceIndex);
        context.getApplicationContext().disconnectAbility(abilityConnection);
        Intent intent = new Intent();
        LogUtils.debug(tag, "connectService.device=" + device);
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId(device.getDeviceId())
                .withBundleName(context.getBundleName())
                .withAbilityName(ServiceAbility.class.getName())
                .build();
        if (!device.getDeviceId().equals("")) {
            intent.addFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE);
        }
        intent.setOperation(operation);
        try {
            boolean result = context.getApplicationContext().connectAbility(intent, abilityConnection);
            return result;
        } catch (Exception e) {
            return false;
        }
    }

    class AbilityConnection implements IAbilityConnection {
        private byte deviceIndex;
        public AbilityConnection(byte i) {
            this.deviceIndex = i;
        }
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
            synchronized (iRemoteObject) {
                MyAgentProxy proxy = new MyAgentProxy(context, iRemoteObject);
                MDevice device = deviceManager.getDevice(deviceIndex);
                if (device == null) {
                    return;
                }
                deviceManager.setCurrentIndex(deviceIndex);
                proxy.byteIndex = deviceIndex;
                deviceManager.getDevice(deviceIndex).setProxy(proxy);
                proxy.addEvent(new EventParam(CONNECTED, deviceIndex));
                proxy.addEvent(new EventParam(GET_PLAY_LIST, proxy.getPlayList()));
                proxy.addEvent(new EventParam(GET_PLAYER_STATE, deviceIndex));
                proxy.addEvent(new EventParam(GET_VOLUME));
                proxy.start();
            }
        }

        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int i) {
            // Service断开时，将DeviceManager中对应设备的代理对象释放
            LogUtils.debug(tag, "onAbilityDisconnectDone.elementName = " + elementName.getDeviceId());
            List<MDevice> deviceList = deviceManager.getDeviceList();
            for (byte pos = 0; pos < deviceList.size(); pos++) {
                if (deviceList.get(pos).getDeviceId().equals(elementName.getDeviceId())) {
                    deviceManager.getDevice(pos).setProxy(null);
                    return;
                }
            }
        }
    }



}
